//
//  FSBaseViewController.m
//  FSScrollViewNestTableViewDemo
//
//  Created by huim on 2017/5/23.
//  Copyright © 2017年 fengshun. All rights reserved.
//

#import "HHBaseViewController.h"
#import "HHBaseTableView.h"
#import "HHBaseTopTableViewCell.h"
#import "FSScrollContentView.h"
#import "HHScrollContentViewController.h"
#import "FSBottomTableViewCell.h"
#import <AlibcTradeSDK/AlibcTradeSDK.h>
#import "SupportCategoryModel.h"
#import "ButtonReusaViewModel.h"
#import "StockHeaderView.h"
#import "SupportCategoryModel.h"
#import "ButtonReusaViewModel.h"
#import "SecondViewCell.h"
#import "SearchViewController.h"
#import "ShoppingGoodsContentViewController.h"
#import "JDKeplerManager.h"
#import "WouldLikeView.h"
#import "UploadShopImageController.h"
#import <SobotKit/ZCLibClient.h>
#import <SobotKit/ZCKitInfo.h>
#import <SobotKit/ZCSobot.h>

@interface HHBaseViewController ()<UITableViewDelegate,UITableViewDataSource,FSPageContentViewDelegate,FSSegmentTitleViewDelegate>
@property (nonatomic, strong) HHBaseTableView *tableView;
@property (nonatomic, strong) FSBottomTableViewCell *contentCell;
@property (nonatomic, strong) FSSegmentTitleView *titleView;
@property (nonatomic, assign) BOOL canScroll;

@property (nonatomic, strong) NSArray *topOneArray;
@property (nonatomic, strong) NSArray *topTwoArray;

@property (nonatomic, assign) CGFloat oneHeight;
@property (nonatomic, assign) CGFloat twoHeight;

@property (nonatomic, strong)  HHScrollContentViewController *vctr;
@property (nonatomic, strong) NSString *classId;
@property (nonatomic, strong) NSString *sortId;

@end

@implementation HHBaseViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.classId = @"0";
    self.sortId = @"1";
    if (@available(iOS 11.0, *)) {
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    UIView *topView = [[UIView alloc] init];
    topView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(Height_StatusBar+50);
    }];
    
    UIButton *searchButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [searchButton setBackgroundImage:[UIImage imageNamed:@"搜索拷贝"] forState:UIControlStateNormal];
    [topView addSubview:searchButton];
    [searchButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.right.mas_equalTo(-10);
        make.height.mas_equalTo(30);
        make.bottom.mas_equalTo(-10);
    }];
     [searchButton addTarget:self action:@selector(preventFlicker:) forControlEvents:UIControlEventAllTouchEvents];
    [searchButton addTarget:self action:@selector(searchBarSearchButton) forControlEvents:UIControlEventTouchUpInside];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeScrollStatus) name:@"leaveTopqqqqq" object:nil];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self setupSubViews];
    
    [self loadSupportCategory];
    
//    UIButton *customerServiceButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    customerServiceButton.backgroundColor = [UIColor grayColor];
//    [self.view addSubview:customerServiceButton];
//    [customerServiceButton mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.right.mas_equalTo(-10);
//        make.bottom.mas_equalTo(-Height_TabBar-30);
//        make.size.mas_equalTo(CGSizeMake(50, 50));
//    }];
//    [customerServiceButton addTarget:self action:@selector(customerServiceButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)customerServiceButtonClick {
    
    
        // 启动
    ZCLibInitInfo *initInfo = [ZCLibInitInfo new];
    initInfo.appKey = @"6d075db1d2ff4a8d92f19d0602e24379";
    initInfo.realName = [CommonUserInfo sharedInstance].nickName?[CommonUserInfo sharedInstance].nickName:[CommonUserInfo sharedInstance].phone;
    initInfo.scopeTime = 48 * 60;
    
    NSString *str = [CommonUserInfo sharedInstance].photoUrl?[CommonUserInfo sharedInstance].photoUrl:@"";
    NSDate *date = [NSDate date];
    long timeSp = (long)[date timeIntervalSince1970];
    NSString *time = [NSString stringWithFormat:@"%ld", (long)timeSp];
    NSString *photoURL = [NSString stringWithFormat:@"%@?timesp=%@", str, time];
    initInfo.avatarUrl = photoURL;
    initInfo.phone = [CommonUserInfo sharedInstance].phone;
        //配置UI
    ZCKitInfo *uiInfo = [ZCKitInfo new];
        // 是否显示转人工按钮
    uiInfo.isShowTansfer = YES;
        // 留言时是否显示昵称
    uiInfo.isShowNickName = YES;
        // 提交留言时，在选择显示昵称之后，选择昵称是否是必填项，如果是必填，昵称提交时不能为空。
    uiInfo.isAddNickName = NO;
    [[ZCLibClient getZCLibClient] setLibInitInfo:initInfo];
    [ZCSobot startZCChatVC:uiInfo with:self target:nil pageBlock:^(id object, ZCPageBlockType type) {
    } messageLinkClick:nil];
    
    
}

- (void)preventFlicker:(UIButton *)button {
    button.highlighted = NO;
}

- (void)searchBarSearchButton {
    SearchViewController *seachCtr = [[SearchViewController alloc] init];
    seachCtr.categoryType = 0;
    [self.navigationController pushViewController:seachCtr animated:NO];
}


#pragma mark -自营商品分类
- (void)loadSupportCategory {
    WS(weakSelf);
    [SupportCategoryModel supportCategoryModelwithSuccess:^(id responseObject) {
        if ([responseObject[@"code"] integerValue] == 1) {
            weakSelf.topOneArray = [SupportCategoryModel mj_objectArrayWithKeyValuesArray:responseObject[@"data"]];
            NSInteger rows = (weakSelf.topOneArray.count - 1) / 4 + 1;
            weakSelf.oneHeight = rows * jisuan(130);
             [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
        }else {
            [[KYAlertView sharedInstance] showAlertViewWithMessage:responseObject[@"msg"]];
        }
        
    } fail:^(NSError *error) {
        if (error) {
            [[KYAlertView sharedInstance] showAlertViewWithMessage:Tip];
        }
    }];
    
    [ButtonReusaViewModel supportButtonModelwithSuccess:^(id responseObject) {
        weakSelf.topTwoArray = (NSArray *)responseObject;
        NSInteger rows = (weakSelf.topTwoArray.count - 1) / 5 + 1;
        weakSelf.twoHeight = rows * ((WIDTH - 2*Margin) / 5.0) + 2*Margin;
         [weakSelf.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    } Fail:^(NSError *error) {
    }];
    
}


- (void)setupSubViews
{
    self.canScroll = YES;
    self.tableView.backgroundColor = [UIColor whiteColor];
}

- (void)insertRowAtTop
{
    NSArray *sortTitles = @[@""];
    self.contentCell.currentTagStr = sortTitles[self.titleView.selectIndex];
    self.contentCell.isRefresh = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    [TalkingData trackPageBegin:@"自营页"];
    WS(weakSelf);
    NSString *sss = [[NSUserDefaults standardUserDefaults] objectForKey:@"popView"];
    if (![sss isEqualToString:@"addddd"]) {
        [[NSUserDefaults standardUserDefaults] setObject:@"addddd" forKey:@"popView"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [QNetWorkRequest autotrophySuccess:^(id response) {
            if ([response[@"data"][@"status"] intValue] != 1) {
                return;
            }
            WouldLikeView *likevv  = [[WouldLikeView alloc] init];
            [weakSelf.view addSubview:likevv];
            [likevv mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.top.bottom.mas_equalTo(0);
            }];
            [likevv.image sd_setImageWithURL:[NSURL URLWithString:response[@"data"][@"imgurl"]]];
            likevv.didSelectBlock = ^{
                if (![[CommonAction sharedInstance] isLoginWithParentVc:self]) {
                    return;
                }
                [weakSelf.navigationController pushViewController:[UploadShopImageController new] animated:YES];
            };
        }];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [TalkingData trackPageEnd:@"自营页"];
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    
}

#pragma mark notify
- (void)changeScrollStatus//改变主视图的状态
{
    self.canScroll = YES;
    self.contentCell.cellCanScroll = NO;
}

#pragma mark UITableView
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    if (section == 0) {
        return 2;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return self.oneHeight + self.twoHeight + 3*Margin;
        } else {
            return jisuan(130);
        }
    }
    return CGRectGetHeight(self.view.bounds);
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    return jisuan(60);
}

- (CGFloat )tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//    self.titleView = [[FSSegmentTitleView alloc]initWithFrame:CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), 50) titles:@[@""] delegate:self indicatorType:FSIndicatorTypeEqualTitle];
//    self.titleView.titleSelectColor = [UIColor whiteColor];
//    self.titleView.indicatorColor = [UIColor whiteColor];
//    self.titleView.backgroundColor = Colorf2f2f2;
    WS(weakSelf);
    StockHeaderView *headerView = [[StockHeaderView alloc] init];
    headerView.stockHeaderViewBlock = ^(NSString * _Nonnull sortId) {
        weakSelf.sortId = sortId;
        [weakSelf.vctr loadDataWithClassId:self.classId SortId:sortId IsUp:YES];
    };
    return headerView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    WS(weakSelf);
    
    static NSString *FSBaseTopTableViewCellIdentifier = @"FSBaseTopTableViewCellIdentifier";
    if (indexPath.section == 1) {
        _contentCell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        if (!_contentCell) {
            _contentCell = [[FSBottomTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
            NSArray *titles = @[@""];
            NSMutableArray *contentVCs = [NSMutableArray array];
            for (NSString *title in titles) {
                self.vctr = [[HHScrollContentViewController alloc]init];
                self.vctr.title = title;
                self.vctr.str = title;
                [contentVCs addObject:self.vctr];
            }
            _contentCell.viewControllers = contentVCs;
            _contentCell.pageContentView = [[FSPageContentView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - Height_StatusBar - 50 - Height_TabBar) childVCs:contentVCs parentVC:self delegate:self];
            [_contentCell.contentView addSubview:_contentCell.pageContentView];
        }
        return _contentCell;
    } else {
        
        if (indexPath.row == 0) {
            HHBaseTopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:FSBaseTopTableViewCellIdentifier];
            if (!cell) {
                cell = [[HHBaseTopTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:FSBaseTopTableViewCellIdentifier];
            }
            cell.oneArray = self.topOneArray;
            cell.twoArray = self.topTwoArray;
            
            cell.topViewCollectionClick = ^(id model, NSInteger section) {
                if (section==0) {
                    SupportCategoryModel *modea = model;
                    
                    if ([modea.type intValue] == 2) {
                        //根据链接打开页面
                        id<AlibcTradePage> page = [AlibcTradePageFactory page:modea.url];
                        AlibcTradeTaokeParams *taoKeParams=[[AlibcTradeTaokeParams alloc] init];
                        taoKeParams.pid= nil;
                        AlibcTradeShowParams* showParam = [[AlibcTradeShowParams alloc] init];
                        showParam.openType = AlibcOpenTypeAuto;
                        [[AlibcTradeSDK sharedInstance].tradeService show: self.navigationController page:page showParams:showParam taoKeParams: nil trackParam: nil tradeProcessSuccessCallback:nil tradeProcessFailedCallback:nil];
                        
                    } else {
                        weakSelf.classId = modea.classId;
                        [self.vctr loadDataWithClassId:modea.classId SortId:weakSelf.sortId IsUp:YES];
                    }
                    
                }else {
                    ButtonReusaViewModel *modele = model;
                    
                    switch (modele.type) {
                        case 0:
                        {
                            WebViewController *webview = [[WebViewController alloc] init];
                            webview.url = modele.url;
                        }
                            break;
                        case 1:
                        {
                        }
                            break;
                        case 2:
                        {
                            //根据链接打开页面
                            id<AlibcTradePage> page = [AlibcTradePageFactory page:modele.url];
                            
                            AlibcTradeTaokeParams *taoKeParams=[[AlibcTradeTaokeParams alloc] init];
                            taoKeParams.pid= nil;
                            //打开方式
                            AlibcTradeShowParams* showParam = [[AlibcTradeShowParams alloc] init];
                            showParam.openType = AlibcOpenTypeAuto;
                            [[AlibcTradeSDK sharedInstance].tradeService show: self.navigationController page:page showParams:showParam taoKeParams: nil trackParam: nil tradeProcessSuccessCallback:nil tradeProcessFailedCallback:nil];
                        }
                            break;
                        case 3:
                        {
                            
                        }
                            break;
                            
                        case 6:
                        {
                            [[JDKeplerManager sharedManager] jumpJDUrl:modele.url Controller:self];
                            
                        }
                            break;
                            
                        default:
                            break;
                    }
                    
                }
            };
            return cell;
        } else {
            
            SecondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondViewCell"];
            return cell;
        }
    
    }
    
}




#pragma mark FSSegmentTitleViewDelegate
- (void)FSContenViewDidEndDecelerating:(FSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.titleView.selectIndex = endIndex;
    _tableView.scrollEnabled = YES;//此处其实是监测scrollview滚动，pageView滚动结束主tableview可以滑动，或者通过手势监听或者kvo，这里只是提供一种实现方式
}

- (void)FSSegmentTitleView:(FSSegmentTitleView *)titleView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex
{
    self.contentCell.pageContentView.contentViewCurrentIndex = endIndex;
}

- (void)FSContentViewDidScroll:(FSPageContentView *)contentView startIndex:(NSInteger)startIndex endIndex:(NSInteger)endIndex progress:(CGFloat)progress
{
    _tableView.scrollEnabled = NO;//pageView开始滚动主tableview禁止滑动
}

#pragma mark UIScrollView
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat bottomCellOffset = [_tableView rectForSection:1].origin.y;
    if (scrollView.contentOffset.y >= bottomCellOffset) {
        scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
        if (self.canScroll) {
            self.canScroll = NO;
            self.contentCell.cellCanScroll = YES;
        }
    }else{
        if (!self.canScroll) {//子视图没到顶部
            scrollView.contentOffset = CGPointMake(0, bottomCellOffset);
        }
    }
//    self.tableView.showsVerticalScrollIndicator = _canScroll?YES:NO;
}

#pragma mark LazyLoad
- (HHBaseTableView *)tableView
{
    if (!_tableView) {
        _tableView = [[HHBaseTableView alloc]initWithFrame:CGRectMake(0, Height_StatusBar+50, CGRectGetWidth(self.view.bounds), HEIGHT - Height_TabBar - Height_StatusBar - 50) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView  setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView registerClass:[SecondViewCell class] forCellReuseIdentifier:@"SecondViewCell"];
        _tableView.tableFooterView = [UIView new];
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

@end
